package com.hj.auth.service.websecurity;

import com.hj.auth.common.convert.UserConvert;
import com.hj.auth.common.pojo.LoginUser;
import com.hj.auth.common.pojo.dto.UserDTO;
import com.hj.auth.common.pojo.entity.User;
import com.hj.auth.mapper.UserMapper;
import com.hj.common.exception.BusinessException;
import com.hj.common.pojo.dirctionary.GenderEnum;
import com.hj.common.pojo.dirctionary.UserStatusEnum;
import com.hj.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PermissionService permissionService;

    @Autowired
    public UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户名 : {}", username);

        //查询用户信息
        User user = userMapper.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            logger.error("登陆用户 : {} 不存在", username);
            throw new BusinessException("用户不存在");
        }

        if (UserStatusEnum.DELETED.getCode().equals(user.getUserStatus())){
            throw new BusinessException("该账号已被删除");
        }

        if (UserStatusEnum.DISABLE.getCode().equals(user.getUserStatus())){
            throw new BusinessException("该账号已被拉入黑名单");
        }
        //查询数据字典 : 设置用户性别
        user.setUserSex(GenderEnum.getInfo(user.getUserSex()));

        //entity转dto
        UserDTO userDTO = UserConvert.INSTANCE.entity2dot(user);

        //查询用户权限信息
        List<String> menuPermission = permissionService.getMenuPermission(userDTO);
        
        return new LoginUser(menuPermission,userDTO);
    }

}
